from conn_mysql_redis import ConnRedis,InsertConnMysql,ConnMysql
import random
import asyncio
import datetime
import json

class SendSms():

    def __init__(self,phone):

        self.phone=phone
        self.send_verify_code=random.randint(100000,999999)

    async def __aenter__(self):
        print("***********进入了***********")
        return self

    async def __aexit__(self,exc_type, exc_val, exc_tb):
        print("*********退出了*************")

        return "退出"
    
    
    async def set_verify_code(self):

        sql = 'SELECT * from user where user_phone=%s'
        info = await ConnMysql().select_one(sql, (self.phone,))

        if not info:

            insert_sql="INSERT INTO user(user_phone) VALUES (%s)"

            await InsertConnMysql().insert_info(insert_sql,(self.phone,))

        with await ConnRedis().pool_ as c:
            await c.select(1)
            await c.set(self.phone,self.send_verify_code)
            await c.expire(self.phone,5*60)
            await c.select(0)

        return {
            'status':1,
            'errorCode':None,
            'errorMsg':None,
            'resultBody':"手机号验证码已保存到缓存中"
        }

    async def can_i_sms(self):
        "是否再次发送短信"
        with await ConnRedis().pool_ as s:
            await s.select(1)
            info=await s.get(self.phone)

        if info:

            return False

        return True

    async def send_sms(self):
 
        if await self.can_i_sms():
     
            print(f"短信已发送，验证码为{self.send_verify_code}")

            return await self.set_verify_code()
    
        return {
            "status": -1,
            "errorCode": 31,
            "errorMsg": '你刚刚已经发送过一条短信',
            "resultBody": None,
            }






      






    




